<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input v-model="params.name" style="width: 200px ; height: 40px" placeholder="请输入姓名"></el-input>
      <el-input v-model="params.phone" style="width: 200px ; height: 40px ; margin-left :5px"
                placeholder="请输入电话"></el-input>
      <el-button type="primary" style="margin-left: 8px" @click="findBySearch()" round>搜索</el-button>
      <el-button type="primary" @click="clean()" round>清空</el-button>
    </div>

    <!--展示医生信息      -->
    <div>
      <el-row>
        <el-col v-for="(doctor,index) in DoctorData" :key="index" :span="4" style="margin-left: 40px ;margin-top: 20px">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div style="padding: 14px;">
              <el-image :src="'http://localhost:8080/yyj/files/'+doctor.img"
                        :preview-src-list="['http://localhost:8080/yyj/files/'+doctor.img]"
                        style="height: 150px;width: 120px"></el-image>
              <span>{{ doctor.name }}</span>
              <div class="bottom clearfix">
                <div class="office">{{ doctor.office }}</div>
                <el-button type="primary" class="button" @click="showDoctor(doctor)">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="block" style="margin-top: 20px">
      <el-pagination
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--显示医生全部信息的对话框  一个嵌套的对话框-->
    <div>
      <el-dialog title="医生详情" :visible.sync="outerVisible">
        <el-image :src="'http://localhost:8080/yyj/files/'+doctorData.img"
                  style="height: 150px;width: 120px;margin-bottom: 30px"></el-image>
        <el-descriptions>

          <el-descriptions-item label="用户名">{{ doctorData.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ doctorData.sex }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ doctorData.age }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ doctorData.phone }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{ doctorData.degree }}</el-descriptions-item>
          <el-descriptions-item label="经历/成就">{{ doctorData.experience }}</el-descriptions-item>
          <el-descriptions-item label="挂号费用">{{ doctorData.price }}</el-descriptions-item>
        </el-descriptions>
        <!--预约弹出来的表单-->
        <el-dialog width="30%" title="预约" :visible.sync="innerVisible" append-to-body>
          <el-form ref="reserveForm" :model="reserveForm" label-width="80px">
            <el-descriptions :column="1" style="margin-left: 10px">

              <el-descriptions-item label="用户">{{ this.user.name }}</el-descriptions-item>
              <el-descriptions-item label="预约医生">{{ doctorData.name }}</el-descriptions-item>
              <el-descriptions-item label="医院地址">哈尔滨市呼兰区师大南路218号</el-descriptions-item>
            </el-descriptions>
            <el-form-item label="预约时间">
              <div class="block" @click="getNum(doctorData.name)">
                <el-cascader
                    v-model="selectedOptions"
                    :options="options"
                ></el-cascader>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit(doctorData.name,doctorData.price)">确认预约信息</el-button>
              <el-button type="warning" @click="innerVisible=false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" @click="outerVisible = false">取 消</el-button>
          <el-button type="primary" @click="cleanSelection()">预约</el-button>
        </div>
      </el-dialog>

      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <span>是否添加到日程</span>
        <span slot="footer" class="dialog-footer">
    <el-button type="warning" @click="dialogVisible = false">否</el-button>
    <el-button type="primary" @click="add()">是</el-button>
  </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "DoctorView",
  data() {
    return {
      selectedOptions: [], // 选中的选项
      options: [],
      params: {
        //是弱语言，不写也行
        name: '',
        phone: '',
        //分页需要传到后端的数据
        pageNum: 1,
        pageSize: 10,
      },
      DoctorData: [],
      total: 0,
      doctorData: {},
      outerVisible: false,
      innerVisible: false,
      reserveForm: {},
      user: localStorage.getItem("user") ? (JSON).parse(localStorage.getItem("user")) : {},
      timeSlotData: {},
      timeSelection: [],
      dialogVisible: false,
      today: '',
      calendar: {},
    }
  },
  //页面生成时需要做的事
  created() {
    this.findBySearch();
    const currentDate = new Date();
    for (let i = 0; i < 7; i++) {
      const date = new Date(currentDate);
      date.setDate(date.getDate() + i+1);

      if (i === 0) {
        this.today = date.toISOString().split('T')[0];
      }
      this.options.push({
        value: date.toISOString().split('T')[0],
        label: date.toISOString().split('T')[0],
      });
    }
    // 填充时间段选项
    for (let i = 0; i < 7; i++) {

      this.options[i].children = [
        {
          value: '8:00-10:00',
          label: '8:00-10:00',
        },
        {
          value: '10:00-12:00',
          label: '10:00-12:00',
        },
        {
          value: '14:00-16:00',
          label: '14:00-16:00',
        },
        {
          value: '16:00-18:00',
          label: '16:00-18:00',
        },
        {
          value: '18:00-20:00',
          label: '18:00-20:00',
        },
      ];

    }


  },
  methods: {
    //添加到日程 时间
    add() {
      //把时间交给数据库查询
      this.calendar.userId = this.user.userId;
      this.calendar.date = this.today;
      this.calendar.content = '预约医生';
      request.post("calendar/saveCalendar", this.calendar).then(res=>{
        if (res.code === '0') {
          this.$message.success("添加成功");
          this.dialogVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    padZero(value) {
      return value < 10 ? `0${value}` : value;
    },
    cleanSelection() {
      this.innerVisible = true
      this.selectedOptions = '';
    },
    //获取选择各个时间段的人数 where doctorName = doctorName
    getNum(doctorName) {
      request.get("/reserve/" + doctorName).then(res => {
        if (res.code === '0') {
          this.timeSelection = res.data;
          for (const item of this.timeSelection) {
            this.timeSlotData[item.timeSelection] = item.appointment_count;
          }
          this.updateOptionsWithDisabled(this.timeSlotData);
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    //处理获取的timeSlotData，进行动态的禁用
    updateOptionsWithDisabled(timeSlotData) {
      this.options = this.options.map(day => {
        day.children = day.children.map(timeSlot => {
          const key = `${day.value},${timeSlot.value}`;
          const maxLimit = 5; // 允许的最大人数
          // 如果此时间段的人数大于或等于限制，则禁用它
          timeSlot.disabled = timeSlotData[key] >= maxLimit;
          return timeSlot;
        });
        return day;
      });
    },
    createDataMap() {
      // Loop through the data and populate the Map
      this.timeSlotData.forEach((item) => {
        this.dataMap.set(item.timeSelection, item.appointment_count);
      });
    },

    onSubmit(doctorName, price) {
      this.reserveForm.doctorName = doctorName;
      this.reserveForm.userName = this.user.name;
      this.reserveForm.price = price;
      this.reserveForm.timeSelection = this.selectedOptions.toString();
      request.post("/reserve/establish", this.reserveForm).then(res => {
        if (res.code === '0') {
          this.$message.success("预约成功");
          this.innerVisible = false;
          this.outerVisible = false;

        } else {
          this.$message.error(res.msg);
        }
      });
      //预约成功之后添加预约信息到日程
      this.dialogVisible = true;
    },

    showDoctor(obj) {
      this.doctorData = obj;
      this.outerVisible = true;
    },
    findBySearch() {
      request.get("/employee/getPostIdOne", {
        params: this.params
      }).then(res => {
        if (res.code === '0') {
          this.DoctorData = res.data.list;
          this.total = res.data.total;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    clean() {
      this.params = {
        name: '',
        phone: '',
        pageNum: 1,
        pageSize: 10
      }
      this.findBySearch();
    }
  }
}
</script>
<style>
.disabled-option {
  color: #ccc; /* 或者其他你想要的禁用选项的样式 */
  cursor: not-allowed; /* 设置鼠标光标为禁用样式 */
}

.office {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.el-image {
  width: 100%;
  display: block;


}

.el-card {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
</style>
